<?php
namespace app\controllers;

use app\logic\CategoryLogic;
use yii;

class CategoryController extends BackendController
{
    const LIMIT=30;

    public function actionIndex(){
        $query = Yii::$app->request->get('form', []);
        $page = Yii::$app->request->get('page', 1);
        $categoryLogic = new CategoryLogic();
        $this->data['breadcrumbs'] = '商品类型管理';
        return $this->render('index', [
            'category' => $categoryLogic->getAllCategory($query, $page),
            'query' => $query
        ]);
    }

    public function actionAdd()
    {
        $categoryLogic = new CategoryLogic();
        if(!Yii::$app->request->post()){
            $this->data['breadcrumbs'] = ['商品类型管理' => U('category/index'), ' 添加类型' => ''];
            return $this->render('add', [
                'theme' => '/assets/',
                'actionUrl' => U('category/add')
            ]);
        }else{
            $params = Yii::$app->request->post('form');
            $logicRes = $categoryLogic->addCategory($params);
            if ($logicRes) {
                Yii::$app->getSession()->setFlash('success','新增类型成功');
                jump('category/index');
            } else {
                Yii::$app->getSession()->setFlash('error','新增类型失败');
                $this->goBack(Yii::$app->request->referrer);
            }
        }
    }

    public function actionEdit()
    {
        $categoryLogic = new CategoryLogic();
        if(!Yii::$app->request->post()){
            $id = Yii::$app->request->get('category_id');
            $category = $categoryLogic->getById($id);
            $this->data['breadcrumbs'] = ['商品类型管理' => U('category/index'), $category['category_name'] => '', '更新' => ''];
            return $this->render('edit', [
                'category'=>$category,
                'theme' => '/assets/',
                'actionUrl' => U('category/edit'),
            ]);
        }else{
            $params = Yii::$app->request->post('form');
            $id = Yii::$app->request->post('category_id');
            $logicRes = $categoryLogic->editById($id, $params);
            if ($logicRes) {
                Yii::$app->getSession()->setFlash('success','更新类型成功');
                jump('category/index');
            } else {
                Yii::$app->getSession()->setFlash('error','更新类型失败');
                $this->goBack(Yii::$app->request->referrer);
            }
        }

    }

    public function actionDelete(){
        $id = Yii::$app->request->get('category_id');
        $categoryLogic = new CategoryLogic();
        $logicRes = $categoryLogic->delete($id);
        if ($logicRes) {
            Yii::$app->getSession()->setFlash('success','删除成功');
        } else {
            Yii::$app->getSession()->setFlash('error','删除失败');
        }
        return $this->redirect(U('category/index'));
    }

}